package com.game.caro.server;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.caro.data.*;
import com.game.caro.util.*;


public class DatabaseAccess 
{
	private static Logger logger = LoggerFactory.getLogger(DatabaseAccess.class);
	/**
	 * @param query them di choi 
	 * @return
	 */
	public ResultSet getResultSet(String query)//ham nay ra ve result set
	{
		logger.debug("Exec Query: " + query + ":");//ham nay`
		ResultSet result =null;
		try 
		{
			Connection connection = DatabaseUtils.getConnection();			
			Statement statement = connection.createStatement();
			result = statement.executeQuery(query);
			
		}
		catch (Exception e) 
		{
			logger.error("GET RESULTSET EXCEPTION = ", e);
		}	 
		return result;
	}
	
	/**
	 * @param query : 
	 * @return
	 */
	public boolean execQuery(String query)//ham nay thuc hien cau lenhe thui, ko quan trong, la 2 ham phuc vu ch
	{
		
			boolean result = false;
			try 
			{
				Connection connection = DatabaseUtils.getConnection();
				Statement statement = connection.createStatement();
				result = statement.execute(query);
				logger.debug("Exec Query: " + query + " ---" + result);
			} 
			catch (Exception e) 
			{
				logger.error("QUERY EXCEPTION=", e);
			}
		
			return	result;
		
	}
	
	public void initRoom()//no dung trong cac ham nay
	{
		ResultSet result = this.getResultSet("select * from room");//no do , ok?, quan trong la ham 
		try
		{
			while (result.next())
		    {   
				PlayRoom playRoom = new PlayRoom();
				playRoom.setRoomID(result.getInt("id"));
				playRoom.setRoomName(result.getString("id"));
				Server.getRooms().put(result.getInt("id"), playRoom);
				logger.info("Creating room: " + playRoom.getRoomID());
			}
		}
		catch(Exception e)
		{
			logger.error("CREATE ROOM EXCEPTION = ", e);
		}
	}
	
	public boolean login(Player player, String username, String password)
	{			
		ResultSet result = this.getResultSet("select * from member where username='" + username + "' and  password='" + password + "'");
		try
		{
			if(result.next())
		    {   
				player.setId(result.getInt("id"));
				player.setName(result.getString("name"));
				player.setUsername(result.getString("username"));				
				player.setPassword(result.getString("password"));
				player.setGender(result.getBoolean("gender"));
				player.setAge(result.getInt("age"));
				player.setWin(result.getInt("win"));
				player.setLose(result.getInt("lose"));
				player.setDissolve(result.getInt("dissolve"));
				return true;
			}
			else
			{
				return false;
			}
		}
		catch(Exception e)
		{
			logger.error("LOGIN CSDL EXCEPTION = ", e);// anh vao chua day?(*)
			return false;
		}
	}
}
